package com.bdqn.ch02.service;

import com.bdqn.ch02.entity.User;
import com.bdqn.ch02.repositroy.UserRepositroy;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class UserImple implements UserService{

    @Resource
    private UserRepositroy userRepositroy;

    public Page<User> findPageByMap(Map param, Pageable pageable) {
        return userRepositroy.findAll(new Specification<User>() {
            @Override
            public Predicate toPredicate(Root<User> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                //拼接查询条件
                List<Predicate> predicates = new ArrayList<>();

                //select * from user where usr like '%zhang%' limit 0,2;
                if (param.get("usrName") != null || !param.get("usrName").equals("")) { //动态 SQL
                    predicates.add(criteriaBuilder.like(root.get("usrName"), "%" + param.get("usrName") + "%"));
                }
                if (param.get("usrPassword") != null || !param.get("usrPassword").equals("")) {
                    predicates.add(criteriaBuilder.equal(root.get("usrPassword"), param.get("usrPassword")));
                }
                return criteriaBuilder.or(predicates.toArray(new Predicate[predicates.size(
                )]));
            }
        }, pageable);
    }
}
